﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Reflection;

namespace FitProtocolLibrary
{
    public class FitFile
    {
        public FitFileHeader Header;
        public Dictionary<FitDefinitionMessage, List<FitDataMessage>> Messages;
        public byte[] Crc;

        public FitFile(byte[] data)
        {
            XmlSerializer xs = new XmlSerializer(typeof(FitProfile));
            TextReader sr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("Profile.xml"));
            FitProfile profile = (FitProfile)xs.Deserialize(sr);

            this.Messages = new Dictionary<FitDefinitionMessage, List<FitDataMessage>>();

            MemoryStream s = new MemoryStream(data);
            BinaryReader r = new BinaryReader(s);

            byte headersize = r.ReadByte();
            byte[] header = new byte[headersize];
            header[0] = headersize;

            for (int i = 1; i < headersize; i++)
            {
                header[i] = r.ReadByte();
            }
            this.Header = new FitFileHeader(header);

            while (s.Position < s.Length - 3)
            {
                FitMessage mesg = new FitMessage(r.ReadByte());

                if (mesg.Header.NormalHeader == 0x00 && mesg.Header.MessageType == 0x01)
                {
                    FitDefinitionMessage defMesg = new FitDefinitionMessage(mesg, profile, r);
                    this.Messages.Add(defMesg, new List<FitDataMessage>());
                }
                else if (mesg.Header.NormalHeader == 0x01 || mesg.Header.MessageType == 0x00)
                {
                    FitDefinitionMessage defMesg = this.Messages.Keys.Last(m => m.Header.LocalMessageType == mesg.Header.LocalMessageType);
                    FitDataMessage dataMesg = new FitDataMessage(mesg, defMesg, r);
                    this.Messages[defMesg].Add(dataMesg);
                }
            }
            this.Crc = new byte[s.Length - s.Position];
            this.Crc = r.ReadBytes(this.Crc.Length);
        }

        public byte[] GetFile()
        {
            throw new NotImplementedException();

            //MemoryStream ms = new MemoryStream();
            //BinaryWriter sw = new BinaryWriter(ms);

            //sw.Write(this.Header.Header);

            //sw.Flush();
            //sw.Close();
            //sw.Dispose();
            //return ms.ToArray();
        }
    }
}
